<template>
  <div>
    <!--  搜索  -->
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-form-item label="商品名称">
        <el-input v-model="formInline.productName" placeholder="商品名称" @keyup.native="selectData"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="selectData">查询</el-button>
        <el-button type="primary" @click="reload">重置</el-button>
        <el-button type="primary" @click="handleEditAdd">新增</el-button>
      </el-form-item>
    </el-form>
    <!--  数据展示  -->
    <el-table
      :data="tableData.slice(5*(this.currentPage-1),(5*this.currentPage))"
      height="320"
      border
      style="width: 100%">
      <el-table-column
        prop="id"
        label="ID"
        width="40">
      </el-table-column>
      <el-table-column
        prop="productCode"
        label="商品编码"
        width="150">
      </el-table-column>
      <el-table-column
        prop="productName"
        label="商品名称"
        width="150">
      </el-table-column>
      <el-table-column
        prop="productPrice"
        label="商品价格"
        width="150">
      </el-table-column>
      <el-table-column
        prop="productAmount"
        label="商品数量"
        width="150">
      </el-table-column>
      <el-table-column
        prop="productType"
        label="商品类型"
        width="150">
      </el-table-column>
      <el-table-column
        v-if="false"
        prop="productTypeId"
        label="商品类型ID"
        width="150">
      </el-table-column>
      <el-table-column
        prop="productShop"
        label="商品店铺"
        width="150">
      </el-table-column>
      <el-table-column
        v-if="false"
        prop="productShopId"
        label="店铺ID"
        width="150">
      </el-table-column>
      <el-table-column align="center" label="操作" min-width="300">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEditUpdate(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="deleteProduct(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--    分页-->
    <el-pagination
      background
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="currentPage"
      :pager-count="5"
      :page-size="5"
      layout="total, prev, pager, next"
      :total="this.tableData.length">
    </el-pagination>
    <!-- 添加界面 -->
    <el-dialog title="添加" :visible.sync="editFormVisibleAdd" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="formInline" :rules="rules" ref="formInline">
        <el-form-item label="商品编号" prop="productCode">
          <el-input size="small" v-model="formInline.productCode" auto-complete="off" placeholder="请输入商品编号"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input size="small" v-model="formInline.productName" auto-complete="off" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="productPrice">
          <el-input size="small" v-model.number="formInline.productPrice" type='number' auto-complete="off"
                    placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="productAmount">
          <el-input size="small" v-model.number="formInline.productAmount" type='number' auto-complete="off"
                    placeholder="请输入商品数量"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-input size="small" v-model="formInline.productType" auto-complete="off" placeholder="商品类型"
                    :disabled="true"></el-input>
          <el-button size="small" @click="handleEditSelect">选择类型</el-button>
        </el-form-item>
        <el-form-item label="商品店铺" prop="productShop">
          <el-input size="small" v-model="formInline.productShop" auto-complete="off" placeholder="商品店铺"
                    :disabled="true"></el-input>
          <el-button size="small" @click="handleEditShopSelect">选择店铺</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitFormAdd('formInline')">添加</el-button>
      </div>
    </el-dialog>
    <!--树形选择商品分类-->
    <el-dialog title="选择类型" :visible.sync="editFormVisibleSelect" width="30%" @click="closeDialog">
      <el-tree
        :data="treeData"
        props="defaultProps"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ data.name }}</span>
        <span>
          <el-button
            type="text"
            size="mini"
            @click="() => selectTreeData(data.id)">
            选择
          </el-button>
        </span>
      </span>
      </el-tree>
    </el-dialog>
    <!--选择店铺-->
    <el-dialog title="选择店铺" :visible.sync="editFormVisibleShopSelect" width="30%" @click="closeDialog">
      <el-table
        :data="shopData"
        height="320"
        border
        style="width: 100%">
        <el-table-column
          prop="id"
          label="ID"
          width="40">
        </el-table-column>
        <el-table-column
          prop="shopName"
          label="店铺名称"
          width="100">
        </el-table-column>
        <el-table-column align="center" label="操作" min-width="100">
          <template slot-scope="scope">
            <el-button size="mini" @click="selectShopData(scope.$index, scope.row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
<!-- 修改商品-->
    <el-dialog title="修改" :visible.sync="editFormVisibleUpdate" width="30%" @click="closeDialog">
      <el-form label-width="120px" :model="formInline" :rules="rules" ref="formInline">
        <el-form-item label="商品编号" prop="productCode">
          <el-input size="small" v-model="formInline.productCode" auto-complete="off" placeholder="请输入商品编号"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" prop="productName">
          <el-input size="small" v-model="formInline.productName" auto-complete="off" placeholder="请输入商品名称"></el-input>
        </el-form-item>
        <el-form-item label="商品价格" prop="productPrice">
          <el-input size="small" v-model.number="formInline.productPrice" type='number' auto-complete="off"
                    placeholder="请输入商品价格"></el-input>
        </el-form-item>
        <el-form-item label="商品数量" prop="productAmount">
          <el-input size="small" v-model.number="formInline.productAmount" type='number' auto-complete="off"
                    placeholder="请输入商品数量"></el-input>
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-input size="small" v-model="formInline.productType" auto-complete="off" placeholder="商品类型"
                    :disabled="true"></el-input>
          <el-button size="small" @click="handleEditSelect">选择类型</el-button>
        </el-form-item>
        <el-form-item label="商品店铺" prop="productShop">
          <el-input size="small" v-model="formInline.productShop" auto-complete="off" placeholder="商品店铺"
                    :disabled="true"></el-input>
          <el-button size="small" @click="handleEditShopSelect">选择店铺</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog">取消</el-button>
        <el-button size="small" @click="reload">重置</el-button>
        <el-button size="small" type="primary" class="title" @click="submitFormUpdate('formInline')">保存</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "productManger",
  created() {
    this.getData()
  },
  data() {
    return {
      editFormVisibleAdd: false,
      editFormVisibleSelect: false,
      editFormVisibleShopSelect: false,
      editFormVisibleUpdate:false,
      formInline: {
        id:'',
        productCode: '',
        productName: '',
        productPrice: '',
        productAmount: '',
        productType: '',
        productTypeId: '',
        productShop: '',
        productShopId: '',
      },
      rules: {
        productCode: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        productName: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        productPrice: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        productAmount: [
          {required: true, message: '请输入', trigger: 'blur'}
        ],
        productType: [
          {required: true, message: '请选择', trigger: 'blur'}
        ],
        productShop: [
          {required: true, message: '请选择', trigger: 'blur'}
        ],
      },
      //商品数据展示
      tableData: [],
      searchTableData: [],
      //商品分类选择数据
      classifyData: [],
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      //店铺选择数据
      shopData: [],
      //分页
      currentPage: "",
    }
  },
  methods: {
    //获取数据
    async getData() {
      var _this = this;
      await this.axios({
        method: "get",
        url: "http://192.168.1.3:8080/getClassify",
      }).then(function (response) {
        response.data.forEach((item) => {
          _this.classifyData.push({
            id: item.id,
            name: item.name,
            parentId: item.parentId,
          })
        })
        _this.treeData = _this.toTree(response.data)
      });
      await this.axios({
        method: "get",
        url: "http://192.168.1.3:8080/getShops",
      }).then(function (response) {
        response.data.forEach((item) => {
          _this.shopData.push({
            id: item.id,
            shopName: item.shopName,
          })
        });
      });
      await this.axios({
        method: "get",
        url: "http://192.168.1.3:8080/getProducts",
      }).then(async function (response) {
        response.data.forEach((item) => {
          var classifyName = _this.getClassifyName(item.productClassify, "")
          var shopName = _this.getShopName(item.productShop,"");
          _this.tableData.push({
            id: item.id,
            productCode: item.productCode,
            productName: item.productName,
            productPrice: item.productPrice,
            productAmount: item.productAmount,
            productType: classifyName,
            productTypeId: item.productClassify,
            productShop:shopName,
            productShopId:item.productShop,
          })
          _this.searchTableData = _this.tableData;
        });
      });
    },
    //模糊查询数据
    selectData() {
      this.tableData = [];
      for (let i = 0; i < this.searchTableData.length; i++) {
        if (this.searchTableData[i].productName.indexOf(this.formInline.productName) >= 0) {
          this.tableData.push(this.searchTableData[i])
        }
      }
    },
    //重置数据
    reload() {
      this.formInline.productCode = "";
      this.formInline.productName = "";
      this.formInline.productPrice = "";
      this.formInline.productAmount = "";
      this.formInline.productType = "";
      this.formInline.productShop = "";
      this.selectData();
    },
    //添加商品
    async submitFormAdd(editData) {
      await this.$refs[editData].validate(async valid => {
        if (valid) {
          await this.$confirm('确定要添加吗?', '信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            var _this = this;
            await this.axios({
              method: "post",
              url: "http://192.168.1.3:8080/addProduct",
              data: {
                productCode: _this.formInline.productCode,
                productName: _this.formInline.productName,
                productPrice: _this.formInline.productPrice,
                productAmount: _this.formInline.productAmount,
                productClassify: _this.formInline.productTypeId,
                productShop: _this.formInline.productShopId,
              },
            }).then(function (response) {
              if (response.data == "Ok") {
                _this.editFormVisibleAdd = false
                _this.$message.success("创建成功")
              } else {
                _this.editFormVisibleAdd = false
                _this.$message.error("创建失败")
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消添加'
            })
          })
          this.tableData = [];
          this.searchTableData = [];
          this.classifyData=[];
          await this.getData();
        } else {
          this.editFormVisibleAdd = false
          this.$message.error('请输入信息')
        }
      })
    },
    //删除商品
    async deleteProduct(index, row) {
      await this.$confirm('确定要删除吗?', '信息', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        var _this = this;
        await this.axios({
          method: "post",
          url: "http://192.168.1.3:8080/deleteProduct",
          data: {
            id: row.id,
          },
        }).then(function (response) {
          if (response.data == "Ok") {
            _this.$message.success("删除成功")
          } else {
            _this.$message.error("删除失败")
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      this.tableData = [];
      this.searchTableData = [];
      this.classifyData=[];
      await this.getData();
    },
    //修改商品
    async submitFormUpdate(editData) {
      await this.$refs[editData].validate(async valid => {
        if (valid) {
          await this.$confirm('确定要保存吗?', '信息', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            var _this = this;
            await this.axios({
              method: "post",
              url: "http://192.168.1.3:8080/updateProduct",
              data: {
                id:_this.formInline.id,
                productCode: _this.formInline.productCode,
                productName: _this.formInline.productName,
                productPrice: _this.formInline.productPrice,
                productAmount: _this.formInline.productAmount,
                productClassify: _this.formInline.productTypeId,
                productShop: _this.formInline.productShopId,
              },
            }).then(function (response) {
              if (response.data == "Ok") {
                _this.editFormVisibleUpdate = false
                _this.$message.success("保存成功")
              } else {
                _this.editFormVisibleUpdate = false
                _this.$message.error("保存失败")
              }
            })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消保存'
            })
          })
          this.tableData = [];
          this.searchTableData = [];
          this.classifyData = [];
          this.shopData= [];
          await this.getData();
        } else {
          this.editFormVisibleUpdate = false
          this.$message.error('请输入信息')
        }
      })
    },
    //获取分类字符串
    getClassifyName(typeId, classifyName) {
      this.classifyData.forEach((item) => {
        if (typeId == item.id) {
          classifyName = item.name + '/' + classifyName
          typeId = item.parentId
          if (typeId != 1) {
            classifyName = this.getClassifyName(typeId, classifyName)
          }
        }
      })
      return classifyName;
    },
    //获取店铺名称
    getShopName(shopId,shopName){
      this.shopData.forEach((item) => {
        if (shopId == item.id) {
          shopName=item.shopName;
        }
      })
      return shopName;
    },
    //json数据转换为tree
    toTree(data) {
      // 删除所有 children,以防止多次调用
      data.forEach(function (item) {
        delete item.children;
      });

      // 将数据存储为 以 id 为 KEY 的 map 索引数据列
      var map = {};
      data.forEach(function (item) {
        map[item.id] = item;
      });

      var val = [];
      data.forEach(function (item) {
        // 以当前遍历项的pid,去map对象中找到索引的id
        var parent = map[item.parentId];
        // 如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
        if (parent) {
          (parent.children || (parent.children = [])).push(item);
        } else {
          //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
          val.push(item);
        }
      });
      return val;
    },
    //树形选择商品分类
    async selectTreeData(id) {
      var classifyName = await this.getClassifyName(id, "")
      this.formInline.productType = classifyName;
      this.formInline.productTypeId = id;
      this.editFormVisibleSelect = false;
    },
    //显示新增商品弹窗
    handleEditAdd() {
      this.editFormVisibleAdd = true
    },
    //显示修改商品弹窗
    handleEditUpdate(index, row){
      this.editFormVisibleUpdate=true;
      this.formInline.id=row.id;
      this.formInline.productCode=row.productCode;
      this.formInline.productName=row.productName;
      this.formInline.productPrice=row.productPrice;
      this.formInline.productAmount=row.productAmount;
      this.formInline.productType=row.productType;
      this.formInline.productTypeId=row.productTypeId;
      this.formInline.productShop=row.productShop;
      this.formInline.productShopId=row.productShopId;
    },
    //显示选择类型窗口
    handleEditSelect() {
      this.editFormVisibleSelect = true;
    },
    //显示选择店铺窗口
    handleEditShopSelect() {
      this.editFormVisibleShopSelect = true;
    },
    //选择店铺
    selectShopData(index, row) {
      this.formInline.productShop = row.shopName;
      this.formInline.productShopId = row.id;
      this.editFormVisibleShopSelect = false;
    },
    // 关闭编辑、增加弹出框
    closeDialog() {
      this.editFormVisibleAdd = false;
      this.editFormVisibleSelect = false;
      this.editFormVisibleShopSelect = false;
      this.editFormVisibleUpdate=false;
    },
    //分页
    handleSizeChange() {
    },
    handleCurrentChange() {
    },
  }
}
</script>

<style scoped>

</style>
